package cn.springcloud.alibaba.ums.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.springcloud.alibaba.ums.vo.AuthorizeVo;
import com.alibaba.nacos.common.utils.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
@RequestMapping("/authorize")
public class AuthorizeController {
	// DefaultAccessTokenConverter
	// @Autowired
	// private AuthFeign authFeign;
	@Autowired
	private RestTemplate restTemplate;
	// @Autowired
	// private StringRedisTemplate stringRedisTemplate;

	/**
	 * 拿code去换取token
	 */
	/*@PostMapping("/token")
	public void token(@RequestBody AuthorizeVo authorizeVo, HttpServletResponse response) throws IOException {
		log.info("authorizeVo:{}", authorizeVo);

		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		headers.add("Content-Type", "multipart/form-data");

		MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
		body.add("client_id", "clientapp");
		body.add("client_secret", "abcd");
		body.add("grant_type", "authorization_code");
		body.add("redirect_uri", "http://127.0.0.1:3000/uaa");

		log.info("[接口名称：调用auth][请求数据body：{}][请求数据headers：{}]", body, headers);

		Object token = authFeign.postAccessToken(body, headers);

		response.sendRedirect("http://127.0.0.1:3000/callback?token=");
	}*/

	/**
	 * 获取登录二维码
	 */
	@GetMapping("/loginQr")
	public void getLoginQr(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		try {
			// 生成uuid给到前端
			String uuid = UuidUtils.generateUuid();
			response.setHeader("uuid", uuid);
			// 这里是开源工具类 hutool里的QrCodeUtil
			// 网址：http://hutool.mydoc.io/
			QrCodeUtil.generate(uuid, 300, 300, "jpg", response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
